package com.fcl.blog.web;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.fcl.blog.comment.Result;
import com.fcl.blog.po.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;


/**
 * @Author 付
 * @Date 2023/10/15 9:51
 * @Version 1.0
 * @description
 * @since 1.0
 */

@Slf4j
@RestController
@RequestMapping("/files")
public class FileController {
//    文件上传存储路径
    // 也就是根目录下 创建一个file文件夹
    private static final String filePath= System.getProperty("user.dir") + "/file/";

//    文件上传
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        synchronized (FileController.class){
            // 获取一个标志，防止文件重名被覆盖
            String flag = System.currentTimeMillis() + "";
            // 获取文件原名
            String filename = file.getOriginalFilename();
            try {
                // 判断是否存在这个文件夹，如果没有就创建
                if (FileUtil.isDirectory(filePath)) {
                    FileUtil.mkdir(filePath);
                }
                // 写文件，将文件写入到指定的文件夹，文件的名称是：flag + 文件原始名称
                FileUtil.writeBytes(file.getBytes(),filePath + flag + "-" + filename);
                Thread.sleep(1L);
                // 这里就可以将flag存储到数据库中
            }catch (Exception e){
                System.out.println("存放的文件地址："+filePath+"---生成的文件名"+filename + "上传失败");
            }
            return  Result.success(flag);
        }

    }
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestPart(value = "file") MultipartFile file) throws IOException {
        System.out.println("filePath==="+filePath);
        File saveFile = new File(filePath);
        if(!saveFile.exists()) {
            saveFile.mkdir();
        }
        String flag = System.currentTimeMillis() + "";
        String saveName = flag+"-"+file.getOriginalFilename();
        String savePathName = filePath+saveName;
        File result = new File(savePathName);
        file.transferTo(result);
        String viewUrl = "http://localhost:8081/image/"+saveName;
        return Result.success("上传成功",viewUrl);
    }


    //    文件下载
    @GetMapping("/{flag}")
    public Result download(@PathVariable String flag, HttpServletResponse response){
        System.out.println("+++++++++++++++++++++++++进来了+++++++++++++++++++++++++++++++++++++++");
        if (FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        // 这里将file下面的所有文件都拿到
        List<String> fileNames = FileUtil.listFileNames(filePath);
        // 循环列表，只要包含了flag，那么就是需要的文件
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        String viewUrl = "http://localhost:8081/image/"+avatar;
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(avatar,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
        }

        return Result.success(viewUrl);
    }

    //删除图片文件，只是删除文件，不删除数据库信息
    @PostMapping("/{flag}")
    @ResponseBody
    public Result delFile(@PathVariable String flag) {
        if (FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }

        String resultInfo="";
        // 这里将file下面的所有文件都拿到
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");


        File file = new File(avatar);
        if (file.exists()) {//文件是否存在
            if (file.delete()) {//存在就删了，返回1
                resultInfo =  "1";
            } else {
                resultInfo =  "0";
            }
        } else {
            resultInfo = "文件不存在！";
        }
        return Result.success("删除成功");
    }

}
